package com.flash.service.impl;

import com.flash.dto.GoodsSalesDTO;
import com.flash.entity.Orders;
import com.flash.mapper.OrderMapper;
import com.flash.mapper.ReportMapper;
import com.flash.mapper.UserMapper;
import com.flash.service.ReportService;
import com.flash.service.WorkspaceService;
import com.flash.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        String dateLists = StringUtils.join(dateList, ",");

        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            // 状态已完成的订单
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);

            HashMap<Object, Object> map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = reportMapper.sumByMap(map);
            turnoverList.add(turnover == null ? 0.0 : turnover);
        }
        String turnoverLists = StringUtils.join(turnoverList, ",");

        return TurnoverReportVO
                .builder()
                .dateList(dateLists)
                .turnoverList(turnoverLists)
                .build();
    }

    /**
     * 用户统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        // 日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        String dateListStr = StringUtils.join(dateList, ",");

        // 用户总量和新用户
        List<Integer> totallUserList = new ArrayList<>();
        List<Integer> newlUserList = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);

            HashMap<Object, Object> map = new HashMap<>();
            map.put("end", endTime);
            Integer totalUser = userMapper.countByMap(map); // 用户总量
            map.put("begin", beginTime);
            Integer newUser = userMapper.countByMap(map); // 新用户

            totallUserList.add(totalUser == null ? 0 : totalUser);
            newlUserList.add(newUser == null ? 0 : newUser);
        }
        String totalUserListStr = StringUtils.join(totallUserList, ",");
        String newUserListStr = StringUtils.join(newlUserList, ",");

        return UserReportVO
                .builder()
                .dateList(dateListStr)
                .totalUserList(totalUserListStr)
                .newUserList(newUserListStr)
                .build();
    }

    /**
     * 订单统计
     *
     * @param begin
     * @param end
     * @return 订单总数和有效订单数
     */
    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        // 日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        Integer totalOrderCount = 0;
        Integer validOrderCount = 0;
        for (LocalDate localDate : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);

            Map<String, Object> map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            Integer dayOrderCount = orderMapper.countByMap(map);//每日订单数
            map.put("status", Orders.COMPLETED);
            Integer dayValidOrderCount = orderMapper.countByMap(map);//每日有效订单数
            dayOrderCount = dayOrderCount == null ? 0 : dayOrderCount;
            dayValidOrderCount = dayValidOrderCount == null ? 0 : dayValidOrderCount;

            orderCountList.add(dayOrderCount);
            validOrderCountList.add(dayValidOrderCount);
            totalOrderCount += dayOrderCount;
            validOrderCount += dayValidOrderCount;
        }

        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(validOrderCount == 0 ? 0 : validOrderCount * 1.0 / totalOrderCount)
                .build();
    }

    /**
     * 销量排名前10
     *
     * @param begin
     * @param end
     */
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        Map<String, Object> map = new HashMap<>();
        map.put("begin", begin);
        map.put("end", end);
        map.put("status", Orders.COMPLETED);
        List<GoodsSalesDTO> list = orderMapper.getSalesTop10(map);

        List<String> nameList = list.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = list.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        return SalesTop10ReportVO
                .builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
    }

    @Override
    public void exportBusinessData(HttpServletResponse res) {
        //1、查询营业数据
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        // 概览数据
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
        //2、将数据写入Excel文件
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template\\运营数据报表模板.xlsx");
        XSSFWorkbook excel = null;
        try {
            excel = new XSSFWorkbook(in);
            XSSFSheet sheet1 = excel.getSheetAt(0);
            sheet1.getRow(1).getCell(1).setCellValue("时间：" + begin + " 至 " + end);

            XSSFRow row3 = sheet1.getRow(3);
            row3.getCell(2).setCellValue(businessData.getTurnover());//营业额
            row3.getCell(4).setCellValue(businessData.getOrderCompletionRate());//有效订单数
            row3.getCell(6).setCellValue(businessData.getNewUsers());//订单完成率

            XSSFRow row4 = sheet1.getRow(4);
            row4.getCell(2).setCellValue(businessData.getValidOrderCount());//平均客单价
            row4.getCell(4).setCellValue(businessData.getUnitPrice());//新增用户数
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                XSSFRow row = sheet1.getRow(i + 7);
                row.getCell(1).setCellValue(date.toString());//日期
                row.getCell(2).setCellValue(businessData.getTurnover());//营业额
                row.getCell(3).setCellValue(businessData.getOrderCompletionRate());//有效订单
                row.getCell(4).setCellValue(businessData.getNewUsers());//订单完成率
                row.getCell(5).setCellValue(businessData.getValidOrderCount());//平均客单价
                row.getCell(6).setCellValue(businessData.getUnitPrice());//新增用户数
            }
            //3、下载到客户端浏览器
            ServletOutputStream out = res.getOutputStream();
            excel.write(out);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (excel != null) excel.close();
                if (in != null) in.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

}
